package com.dpiinc.TechPage.user;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dpiinc.TechPage.AIWriteApplication;
import com.dpiinc.TechPage.BaseActivity;
import com.dpiinc.TechPage.R;
import com.dpiinc.TechPage.widget.ProgressView;

import java.io.ByteArrayInputStream;
import java.security.MessageDigest;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Locale;

public class VideoWebViewActivity extends BaseActivity {
    private RelativeLayout mRelativeLayout;
    private WebView mWebView;
    private MyWebChromeClient mMyWebChromeClient;

    public static final String URL_KEY = "url_key";
    public static final String TITLE_KEY = "title_key";
    private String url;
    private String title;

    private ProgressView progressView;//进度条
    private Context context;

    /**
     * 跳转到Webview
     *
     * @param context Context
     * @param url     url地址
     */
    public static void webviewEntrance(Context context, String url, String title) {
        Intent intent = new Intent(context, VideoWebViewActivity.class);
        intent.putExtra(URL_KEY, url);
        intent.putExtra(TITLE_KEY, title);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle bundle) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(bundle);
        setContentView(R.layout.activity_video_webview);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
        if (toolbar != null) {
            //设置toolbar
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle("");
            toolbar.setNavigationIcon(R.drawable.toolbar_back);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onBackPressed();
                }
            });
        }
        mRelativeLayout = findViewById(R.id.mRelativeLayout);
        mWebView = findViewById(R.id.h5_video_webview);
        initWebView();
        mWebView.loadUrl(url);
        //获取配置语言，未配置为默认语言
        String app_language = getSharedPreferences("app_language",Context.MODE_PRIVATE).getString("lauType",Locale.getDefault().getLanguage());
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        config.locale = new Locale(app_language,"");
        resources.updateConfiguration(config,resources.getDisplayMetrics());
        AIWriteApplication.Companion.instance().updateLanguage();
    }

    private void init() {
        Intent intent = getIntent();
        url = intent.getStringExtra(URL_KEY);
        title = intent.getStringExtra(TITLE_KEY);
        context = getApplicationContext();
    }

    private void initWebView() {
        init();
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(title);
        if (TextUtils.isEmpty(url)) {
//            toast("url不能为空");
            return;
        }

        //初始化进度条
        progressView = new ProgressView(context);
        progressView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp2px(context, 4)));
        int getcolor = getResources().getColor(R.color.color_00bad2);
        progressView.setColor(getcolor);
        progressView.setProgress(10);
        //把进度条加到Webview中
        mWebView.addView(progressView);

        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setLoadWithOverviewMode(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        settings.setUseWideViewPort(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        mMyWebChromeClient = new MyWebChromeClient();
        mWebView.setWebChromeClient(mMyWebChromeClient);
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                Log.e("TTT", "shouldInterceptRequest 0 url is " + url);
                //回调发生在子线程中,不能直接进行UI操作
                return super.shouldInterceptRequest(view, url);
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                Log.e("TTT", "shouldInterceptRequest 1 request url is " + request.getUrl().toString());
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){
                Log.e("TTT", "onReceivedSslError");
//            handler.proceed();

                if (error.getPrimaryError() == SslError.SSL_DATE_INVALID  // 日期不正确
                        || error.getPrimaryError() == SslError.SSL_EXPIRED // 日期不正确
                        || error.getPrimaryError() == SslError.SSL_INVALID // webview BUG
                        || error.getPrimaryError() == SslError.SSL_UNTRUSTED) { // 根证书丢失
                    if (chkMySSLCNCert(error.getCertificate())) {
                        handler.proceed();  // 如果证书一致，忽略错误
                    }
                }
            }

            private boolean chkMySSLCNCert(SslCertificate cert) {
                byte[] MySSLCNSHA256 = { -116, -71, 79, 2, -35, -82, 74, 77, 95, 2, -128,
                        121, 15, -26, -87, -89, -38, -106, 71, -42, 76, 125, -26, 70, -11, 95, 66,
                        14, 107, 9, 84, -75 };  //证书指纹
                Bundle bundle = SslCertificate.saveState(cert);
                byte[] bytes = bundle.getByteArray("x509-certificate");
                if (bytes != null) {
                    try {
                        CertificateFactory cf = CertificateFactory.getInstance("X.509");
                        Certificate ca = cf.generateCertificate(new ByteArrayInputStream(bytes));
                        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
                        byte[] key = sha256.digest(ca.getEncoded());
                        return Arrays.equals(key, MySSLCNSHA256);
                    } catch (Exception Ex) {}
                }
                return false;
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        mWebView.reload();
    }

    private class MyWebChromeClient extends WebChromeClient {
        private View mCustomView;
        private CustomViewCallback mCustomViewCallback;

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                //加载完毕进度条消失
                progressView.setVisibility(View.GONE);
            } else {
                //更新进度
                progressView.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            mCustomView = view;
            mRelativeLayout.addView(mCustomView);
            mRelativeLayout.setVisibility(View.VISIBLE);
            mCustomViewCallback = callback;
            mWebView.setVisibility(View.INVISIBLE);
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            mRelativeLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        }

        public void onHideCustomView() {
            mWebView.setVisibility(View.VISIBLE);
            if (mCustomView == null) {
                return;
            }
            mCustomView.setVisibility(View.GONE);
            mRelativeLayout.removeAllViews();//移除所有控件
            mRelativeLayout.setVisibility(View.GONE);//隐藏播放布局
            mCustomViewCallback.onCustomViewHidden();
            mCustomView = null;
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mRelativeLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            super.onHideCustomView();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }

    @Override
    public void onPause() {
        mWebView.onPause();
        mWebView.pauseTimers();
        super.onPause();
    }

    @Override
    public void onResume() {
        mWebView.onResume();
        mWebView.resumeTimers();
        super.onResume();

    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            mWebView.loadUrl("about:blank");
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onDestroy() {
        mWebView.destroy();
        mWebView = null;
        super.onDestroy();
    }

    /**
     * dp转换成px
     *
     * @param context Context
     * @param dp      dp
     * @return px值
     */
    private int dp2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            mWebView.loadUrl("about:blank");
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }
}
